package com.zx.disneyholidays.page.login;

import android.util.Log;
import android.widget.Toast;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.alibaba.fastjson.JSONObject;
import com.tencent.mmkv.MMKV;
import com.zx.disneyholidays.MyApplication;
import com.zx.disneyholidays.Task;
import com.zx.disneyholidays.net.BaseResponse;
import com.zx.disneyholidays.net.HttpUtils;
import com.zx.disneyholidays.net.ResponseCallBack;
import com.zx.disneyholidays.page.LoginActivity;

import java.util.HashMap;
import java.util.Map;

public class LoginViewModel extends ViewModel {
    public MutableLiveData<Boolean> loginMutableLiveData = new MutableLiveData<>();

    public void login(String phoneNumber) {
        Map<String, String> params = new HashMap<>();
        params.put("phone", phoneNumber);
        HttpUtils.instance.httpPost("api/index/login", JSONObject.toJSONString(params), new ResponseCallBack() {
            @Override
            public void onSuccess(BaseResponse data) {
                if (data.getCode() != 1) {
                    Toast.makeText(MyApplication.applicationContext, data.getMsg(), Toast.LENGTH_SHORT).show();
                    return;
                }

                Log.d("xxx", data.getData());
                JSONObject object = JSONObject.parseObject(data.getData());
                MMKV.defaultMMKV().encode("token", object.getString("token"));
                MMKV.defaultMMKV().encode("userName", object.getString("username"));
                loginMutableLiveData.setValue(true);
            }

            @Override
            public void onError(int error, String msg) {
                Toast.makeText(MyApplication.applicationContext, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
